package com.meowcook.exception;


import com.meowcook.common.AppResult;
import com.meowcook.common.ResultCode;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MaxUploadSizeExceededException;

@Slf4j
@ControllerAdvice
public class GlobalExceptionHandler {

    @ResponseBody
    @ExceptionHandler(AppException.class)
    public AppResult<Object> handleAppException(AppException e){
        // 打印异常信息
        e.printStackTrace();
        //记录日志
        log.error(e.getMessage());
        //获取异常信息
        if (e.getErrorResult() != null){
            // 返回异常类中记录的信息
            return e.getErrorResult();
        }
        // 返回默认的错误信息
        return AppResult.fail(e.getMessage());
    }

    @ResponseBody
    @ExceptionHandler(MaxUploadSizeExceededException.class)
    public AppResult<Object> handleMaxUploadSizeExceededException(MaxUploadSizeExceededException e){
        // 打印异常信息
        e.printStackTrace();
        //记录日志
        log.error(e.getMessage());
        // 返回默认的错误信息
        return AppResult.fail("图片大小不能超过: 10MB");
    }

    @ResponseBody
    @ExceptionHandler(FileUploadException.class)
    public AppResult<Object> handleFileUploadException(FileUploadException e){
        // 打印异常信息
        e.printStackTrace();
        //记录日志
        log.error(e.getMessage());
        // 返回默认的错误信息
        return AppResult.fail(e.getMessage());
    }

    @ResponseBody
    @ExceptionHandler(Exception.class)
    public AppResult<Object> handleException(Exception e){
        // 打印异常信息
        e.printStackTrace();
        //记录日志
        log.error(e.getMessage());

        if (e.getMessage() == null){
            return AppResult.fail(ResultCode.ERROR_SERVICE);
        }
        //返回默认的错误信息
        return AppResult.fail(e.getMessage());
    }


    @ResponseBody
    @ExceptionHandler(LoginElseException.class)
    public AppResult<Object> handleLoginElseException(LoginElseException e){
        //返回默认的错误信息
        return AppResult.fail(ResultCode.FAIL_USER_LOGIN_ELSEWHERE);
    }
}
